package com.xxwy.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;


/**
 * @author wy
 * @date 2020/3/6 10:13
 */
public class ServerHandler extends SimpleChannelInboundHandler<String> {

  /**
   * 定义一个Channel组
   */
  private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

  /**
   * 表示建立连接，一旦建立连接，第一个被执行
   * @param ctx
   * @throws Exception
   */
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    //推送 xxx来到聊天室
    channelGroup.writeAndFlush("客户端 ：" + channel.remoteAddress() + "来到聊天室");
    channelGroup.add(channel);
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    System.out.println("客户端 ：" + channel.remoteAddress() +"上线");
  }

  /**
   * 便是channel处于不活跃状态
   * @param ctx
   * @throws Exception
   */
  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    System.out.println("客户端 ：" + channel.remoteAddress() +"离线");
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    Channel channel = ctx.channel();
    //推送 xxx离开聊天室
    //channelGroup.remove(channel); 自动删除
    channelGroup.writeAndFlush("客户端 ：" + channel.remoteAddress() + "离开聊天室");
    System.out.println("groupchat size:" + channelGroup.size());
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    Channel channel = ctx.channel();
    channelGroup.forEach(ch->{
      if(channel!=ch){
        ch.writeAndFlush("客户 " + channel.remoteAddress() +"发送了消息" + msg+"\n");
      }else {
        ch.writeAndFlush("[已读]");
      }
    });
  }


}
